<template>
  <div class="pagination">
    <button
      :disabled="currentPageNo === 1"
      @click="$emit('changeNo', currentPageNo - 1)"
    >
      上一页
    </button>

    <button v-if="startEnd.start > 1" @click="$emit('changeNo', 1)">1</button>

    <button v-if="startEnd.start > 2">···</button>
    <!--  v-for 可以和 v-if同时使用  v-for优先级高 -->
    <button
      :class="{ active: page === currentPageNo }"
      v-for="page in startEnd.end"
      :key="page"
      v-if="page >= startEnd.start"
      @click="$emit('changeNo', page)"
    >
      {{ page }}
    </button>

    <button v-if="startEnd.end < totalPageNo - 1">···</button>

    <button
      v-if="startEnd.end < totalPageNo"
      @click="$emit('changeNo', totalPageNo)"
    >
      {{ totalPageNo }}
    </button>

    <button
      :disabled="currentPageNo === totalPageNo"
      @click="$emit('changeNo', currentPageNo + 1)"
    >
      下一页
    </button>

    <button style="margin-left: 30px">共 {{ total }} 条</button>
  </div>
</template>

<script>
export default {
  name: "Pagination",
  //   props 接受的属性数据  computed计算的数据  以及data里面的数据
  //   最终可以通过vm访问
  props: {
    currentPageNo: {
      type: Number,
      required: true,
    },
    total: {
      type: Number,
      default: 0,
    },
    pageSize: {
      tpye: Number,
      required: true,
    },
    continueNum: {
      type: Number,
      default: 5,
    },
  },

  computed: {
    //  计算总页数
    totalPageNo() {
      return Math.ceil(this.total / this.pageSize);
    },

    //  根据当前业的不同计算连续页的起始位置和结束位置
    startEnd() {
      let { currentPageNo, continueNum, totalPageNo } = this;
      let start = 0,
        end = 0;
      // 先考虑总页码比连续数还小
      if (continueNum > totalPageNo) {
        start = 1;
        end = totalPageNo;
      } else {
        // 先考虑所有的都是中间情况
        start = currentPageNo - Math.floor(continueNum / 2);
        end = currentPageNo + Math.floor(continueNum / 2);
        // 在左侧不正常需要修正
        if (start < 1) {
          start = 1;
          end = continueNum;
        }
        // 在右侧不正常需要修正
        if (end > totalPageNo) {
          end = totalPageNo;
          start = totalPageNo - continueNum + 1;
        }
      }

      return { start, end };
    },
  },
};
</script>

<style lang="less" scoped>
.pagination {
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      //   cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>
